<?php

namespace App\Http\Services;

use App\Models\Advice;
use App\Models\Chat;
use App\Models\WechatTest;
use App\Repositories\Api\AdviceRepository;
use Hhxsv5\LaravelS\Swoole\WebSocketHandlerInterface;
use Illuminate\Support\Facades\Log;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class WebSocketService implements WebSocketHandlerInterface
{

    public function __construct()
    {

        $this->mssageLists = [
            "测试数据1",
            "测试数据2",
            "测试数据3",
            "测试数据4",
        ];
    }

//    private $request_id = 1;
    public function onOpen(Server $server, Request $request)
    {
        Log::info('WebSocket 连接建立');
        $server->push($request->fd, 'Welcome to WebSocket Server built on LaravelS 333333');
        // file_put_contents('/tmp/webscoker.log', "open socket: " . $request->fd . date("Y-m-d H:i:s") . "\n\n\n", 8);

    }

    public function onMessage(Server $server, Frame $frame)
    {
        $data = json_decode($frame->data, true);
        // file_put_contents('/tmp/webscoker.log', "scoket  111 on Message:  $frame->fd \n" . var_export($data, true) . "\n\n\n", 8);

        switch ($data['type']) {
            case "advice":
                if ($data['action'] == 'reply') { // 消息回复

                    $adviceData['uid'] = $data['from_uid'];
                    $adviceData['content'] = $data['data'];
                    $adviceData['pid'] = intval($data['pid']);
                    $adviceData['is_read'] = 2;
                    $adviceData['create_time'] = date("Y-m-d H:i:s");

                    $last_id = Advice::insertGetId($adviceData);
                    $advice = Advice::query()->where("id", "=", $last_id)->first();
                    file_put_contents('/tmp/webscoker.log', "scoket on advice:  $frame->fd , advice_id : $last_id \n\n", 8);

                    $server->push($frame->fd, json_encode($advice));
                } else if ($data['action'] == 'unread') { //获取未读信息
                    file_put_contents('/tmp/webscoker.log', "scoket on advice:  unread \n\n", 8);

                    if (!empty($data['advice_id'])) {
                        $advice = Advice::query()->where("id", "=", $data['advice_id'])->first();
                        if ($advice['uid'] == $data['from_uid']) {
                            //对方id
                            $replyList = (new AdviceRepository())->getReplyList(['pid' => $advice['id'], 'not_uid' => $advice['uid'], 'is_read' => 2]);
                        } else {
                            // 获取对方信息
                            $replyList = (new AdviceRepository())->getReplyList(['pid' => $advice['id'], 'not_uid' => $data['from_uid'], 'is_read' => 2]);

                            if ($replyList['total']) {
                                $adviceIds = get_column($replyList['items'], "id");
                                Advice::whereIn("id", $adviceIds)->update(['read_time' => date("Y-m-d H:i:s"), 'is_read' => 1]);
                                file_put_contents('/tmp/webscoker.log', "scoket on advice:  ids " . var_export($adviceIds, true) . "\n\n", 8);
                            }
                            $server->push($frame->fd, json_encode($replyList['items']));
                        }
                    }
                }

                break;
            case "chat":
                $chat_data = [
                    'uid' => $data['from'],
                    'df_uid' => $data['to'],
                    'content' => $data['data']
                ];

                $res = Chat::create($chat_data);
                // 判断是否有chat Fd ToDo  有信息推送给对方
                $df_fd = ChatFd::where(['uid' => $chat_data])->value("fd");
                $this->_send_chat_msg($server, $chat_data['df_uid'], $chat_data['uid']);
                /*
                // 推送给对方
                $unreadList = Chat::where(['uid' => $data['to'], 'df_uid' => $data['from']])->whereNull("read_time")->orderBy("id", "desc")->get()->toArray();

                // 读取未读信息
                if ($unreadList) {
                    $ids = get_column($unreadList, "id");
                    foreach ($unreadList as $k => &$v) {
                        $v['add_time_format'] = HumanTime($v['create_time']);
                    }

                    sort($unreadList);
                    $res = $server->push($frame->fd, json_encode($unreadList));
                    if($res){
                        Chat::whereIn("id", $ids)->update(['read_time' => date("Y-m-d H:i:s")]);
                    }
                }*/
                // $server->push($frame->fd, json_encode($data));
                break;
            default:
                break;
        }
    }

    //关闭链接
    public function onClose(Server $server, $fd, $reactorId)
    {
        // TODO: Implement onClose() method.
        Log::info('WebSocket 连接关闭');
        file_put_contents('/tmp/webscoker.log', "WebSocket 连接关闭:  " . $fd . " \n", 8);
    }

    private function _send_chat_msg($server, $uid = null, $df_uid = null)
    {
        // 推送给对方
        $unreadList = Chat::where(['uid' => $df_uid, 'df_uid' => $uid])->whereNull("read_time")
            ->orderBy("id", "desc")->get()
            ->toArray();

        if (empty($unreadList)) return false;

        $ids = get_column($unreadList, "id");
        foreach ($unreadList as $k => &$v) {
            $v['add_time_format'] = HumanTime($v['create_time']);
        }

        sort($unreadList);
        $res = $server->push($frame->fd, json_encode($unreadList));
        if ($res) {
            Chat::whereIn("id", $ids)->update(['read_time' => date("Y-m-d H:i:s")]);
        }
    }
}